package com.newcoretech.platform_service.scanner.thread;///

import android.content.Context;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

/// * @ProjectName: scanner
/// * @Author: qifanxin
/// * @CreateDate: 2022/3/22 2:02 下午
/// * Copyright: ©2022 NEW CORE Technology Co. Ltd. All rights reserved.
/// * @Description: 文件说明
///
public class QRCodeProcessThread implements Callable<List<String>> {

    ///任务的图片路径
    private List<String> taskList;

    private Context mContext;

    public QRCodeProcessThread(List<String> taskList, Context context) {
        this.taskList = taskList;
        this.mContext = context;
    }

    @Override
    public List<String> call() throws Exception {
        if (taskList == null || taskList.isEmpty()) {
            return null;
        }
        ///返回结果，由于需要传递给子线程进行操作，所以用线程安全类
        CopyOnWriteArrayList<String> resList = new CopyOnWriteArrayList();
        ///开启固定数量线程池，防止资源耗尽
        ExecutorService threadPool = null;
        try {
            ///计数锁
            CountDownLatch countDownLatch = new CountDownLatch(taskList.size());
            threadPool = Executors.newFixedThreadPool(taskList.size());
            for (String path : taskList) {
                QRCodeReadThread qrCodeReadThread = new QRCodeReadThread();
                qrCodeReadThread.setData(countDownLatch, resList, path, mContext);
                threadPool.execute(qrCodeReadThread);
            }
            countDownLatch.await();
            return resList.subList(0, taskList.size());
        } catch (Exception e) {
            return null;
        } finally {
            if(threadPool != null) {
                threadPool.shutdown();
            }
        }
    }
}
